//
//  SaleViewController.m
//  NewBook
//
//  Created by dlios on 15-3-8.
//  Copyright (c) 2015年 dlios. All rights reserved.
//

#import "SaleViewController.h"

@interface SaleViewController ()

@end

@implementation SaleViewController

-(void)dealloc
{
    [_myTableView release];
    [_allSaleBookArray release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
  //-----------------------导航栏---------------------------------
    //设置图片不被渲染
    UIImage *backImage = [UIImage imageNamed:@"iconfont-fanhui.png"];
    backImage = [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //返回键
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem = backButton;
    self.navigationItem.title = @"特价优惠";

  //---------------------------------------------------------------
    
    self.view.backgroundColor = [UIColor grayColor];
        //初始化数组
    self.allSaleBookArray = [NSMutableArray array];
    self.isUpLoading = NO;
    //创建tableView,用来显示
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60 - 19) style:UITableViewStylePlain];
    self.myTableView.rowHeight = 183;
    //把tableView的分割线去掉
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [_myTableView release];

    
    [self addHeader];
    [self addFooter];
    

}


//下拉刷新
- (void)addHeader
{
    //NSLog(@"下拉刷新");
    __block SaleViewController *movieVC = self;
    [self.myTableView addHeaderWithCallback:^{
        //NSLog(@"222");
        movieVC.isUpLoading = NO;
        [self GetMovieList:0];
    }];
    [self.myTableView headerBeginRefreshing];
}
//上拉加载
- (void)addFooter
{
    //NSLog(@"上拉刷新");
    __block SaleViewController *movieVC = self;
    [self.myTableView addFooterWithCallback:^{
        //NSLog(@"333");
        movieVC.isUpLoading = YES;
        [movieVC GetMovieList:movieVC.page];
        
    }];
}
//AFN请求数据
- (void)GetMovieList:(NSInteger)page
{
   // NSLog(@"88888888");
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    NSString *url_string = [NSString stringWithFormat:@"http://mapi.dangdang.com/index.php?action=list_category&user_client=iphone&client_version=5.0.1&page=%ld&page_size=7&sort_type=default_0&cid=01.01.00.00.00.00&img_size=h&udid=18948B21919333DDC1DDE273A67E5005&time_code=CAC30CE21A9B7F3ED5B12910AB91E139&timestamp=1425611852&union_id=537-50&permanent_id=20150304193014100686115327268485015",page + 1];
    
   // NSLog(@"url = %@",url_string);
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        
        
        NSDictionary *saleDic = responseObject;
        //NSLog(@"使用AFN进行get请求 ===  %@",saleDic);
        
        //记录下一页
        //先取出saleDic字典下的page字典
        NSMutableDictionary *pageDic = [saleDic objectForKey:@"page"];
        //然后取出pageDic字典下对应的pageindex内容
        self.page = [[pageDic objectForKey:@"pageindex"] integerValue];
        //NSLog(@"nextCursor == %ld",self.page);
       
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.allSaleBookArray removeAllObjects];
        }
        
        
        NSArray *array = [saleDic objectForKey:@"products"];
        for (NSDictionary *dic  in array) {
            
            BookSale *bookSale = [[BookSale alloc] init];
//            bookSale.image_url = [dic objectForKey:@"image_url"];
            [bookSale setValuesForKeysWithDictionary:dic];
            bookSale.productId = [dic objectForKey:@"id"];
            [self.allSaleBookArray addObject:bookSale];
           // NSLog(@"gggg=%@", bookSale.name);
        }
        
        
        [self.myTableView footerEndRefreshing];//结束底部刷新效果
        [self.myTableView headerEndRefreshing];//结束头部刷新效果
        [self.myTableView reloadData];//刷新tableview
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}


//tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allSaleBookArray.count;
}
//tableview上cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 94;
}
//tableview上cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SaleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        cell = [[SaleTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ID"];
    }
    //将cell设置成点击时不变色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BookSale *bookSale = [self.allSaleBookArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:bookSale.image_url];
    //sd请求图片
    [cell.bookCoverImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"picLib_default@2x.png"]];
    //重新赋值
    cell.bookNameLable.text = bookSale.name;
    cell.bookReferLable.text = bookSale.subname;
    cell.salePriceLable.text = bookSale.dd_sale_price;
    cell.originalPriceLable.text = bookSale.original_price;
       return cell;
}
//导航栏左侧的返回按钮
- (void)backBarButtonItemAction:(UIBarButtonItem *)barButton
{
    [self.navigationController popViewControllerAnimated:YES];
}






//点击cell跳转详情页面方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookDetailsViewController *bookDetailsVC = [[BookDetailsViewController alloc] init];
    BookSale *bookSale = [self.allSaleBookArray objectAtIndex:indexPath.row];
    //为详情页面各个模块赋值
    bookDetailsVC.title = bookSale.name;
    bookDetailsVC.nameStr = bookSale.name;
    bookDetailsVC.authornameStr = bookSale.authorname;
    bookDetailsVC.subNameStr = bookSale.subname;
    bookDetailsVC.priceStr = [NSString stringWithFormat:@"￥ :    %@",bookSale.dd_sale_price];
    bookDetailsVC.detailsImageStr = bookSale.image_url;
    bookDetailsVC.productId = bookSale.productId;
    //    NSURL *url = [NSURL URLWithString:bookSale.image_url];
    //    [bookDetailsVC.detailsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"picLib_default@2x.png"]];
    //NSLog(@"333333333333%@",bookDetailsVC.nameLabel.text);
    
    
    
    //NSLog(@"1111111111111111111%@",self.allSaleBookArray);
    
    
    [self.navigationController pushViewController:bookDetailsVC animated:YES];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
